package com.estronger.shopmanage.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;

import com.estronger.shopmanage.ui.common.OpenPdfActivity;
import com.estronger.shopmanage.ui.othertask.bean.FileBean;
import com.github.dfqin.grantor.PermissionListener;
import com.soonfor.evaluate.http.httptools.AsyncUtils;
import com.soonfor.evaluate.tools.PermissionsCheckUtil;

import java.io.File;
import java.util.Locale;


/**
 * 打开附件
 */
public class OpenFileUtil {

    public static void show(final Context mContext, final FileBean fileBean, final CallBack callBack){
        if (fileBean == null) {
            Toast.show(mContext, "附件路径为空！", Toast.LENGTH_SHORT);
            return;
        }
        PermissionsCheckUtil.requestPermission(mContext, new PermissionListener() {
                    @Override
                    public void permissionGranted(@NonNull String[] permissions) {
                        String fileUrl = fileBean.getAttachUrl();
                        if (fileUrl.equals("")) {
                            Toast.show(mContext, "附件路径为空！", Toast.LENGTH_SHORT);
                        } else {
                            String fileName = fileBean.getAttachName();
                            String fileFormat = fileBean.getFileFormat();
                            if (fileUrl.startsWith("/storage") || fileUrl.startsWith("/data")) {
                                //本地附件
                                if (callBack != null) callBack.startLoadingDialog();
                                if (fileFormat.trim().equalsIgnoreCase("pdf")) {
                                    //打开pdf
                                    Intent intent = new Intent(mContext, OpenPdfActivity.class);
                                    intent.putExtra("title", fileName);
                                    intent.putExtra("path", fileUrl);
                                    mContext.startActivity(intent);
                                }else {
                                    FileUtils.openFile(mContext, fileUrl);
                                }
                                if (callBack != null) callBack.endLoadingDialog();
                            } else {
                                //网络附件
                                String fileType = "";
                                if (fileUrl.contains("?filepath=")) {
                                    fileType = "text/plain";
                                    if (!fileUrl.startsWith("http")) fileUrl =  ("/" + fileUrl);//DataTools.getServiceAddress(1) +
                                } else {
                                    fileType = "file";
                                    if (!fileUrl.startsWith("http")){
                                        fileUrl = (fileUrl.startsWith("/") ? fileUrl : ("/" + fileUrl));//DataTools.getServiceAddress(3) +
                                    }
                                }
                                if (fileFormat.trim().equalsIgnoreCase("pdf")) {
                                    //打开pdf
                                    Intent intent = new Intent(mContext, OpenPdfActivity.class);
                                    intent.putExtra("title", fileName);
                                    intent.putExtra("path", fileUrl);
                                    intent.putExtra("fileType", fileType);
                                    mContext.startActivity(intent);
                                }else {
                                    //先看下暂存的文件夹中是否已下载
                                    if (callBack != null) callBack.startLoadingDialog();
                                    String exsitPath = FileUtils.isExistInTheDir("HomeCase", fileName);
                                    if (exsitPath == null) {
                                        //不存在则下载
                                        downLoadFile(mContext, fileType, fileName, fileUrl, "HomeCase", callBack);
                                    }else {
                                        FileUtils.openFile(mContext, exsitPath);
                                        if (callBack != null) callBack.endLoadingDialog();
                                    }
                                }
                            }
                        }
                    }

                    @Override
                    public void permissionDenied(@NonNull String[] permissions) {
                        Toast.show(mContext, "您拒绝了存储权限，无法下载查看", Toast.LENGTH_SHORT);
                    }
                }, Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }
    //下载附件
    private static void downLoadFile(Context context, String fileType, String fileName, String url, String storeDir, CallBack callBack) {
//        AsyncUtils.downloadFileFromCrm(context, fileType, fileName, url, storeDir, 1000, new AsyncUtils.AsyncCallback2() {
//            @Override
//            public void success(String type, int requestCode, String data) {
//                FileUtils.openFile(context, data);
//                if (callBack != null) callBack.endLoadingDialog();
//            }
//
//            @Override
//            public void onProgress(String type, int requestCode, int count) {
//                if (callBack != null) callBack.onDownloadProgress();
//            }
//
//            @Override
//            public void fail(String type, int requestCode, int statusCode, String msg) {
//                if (callBack != null) callBack.endLoadingDialog();
//                MyToast.showToast(context, msg);
//            }
//        });
    }

    private static String[] types = new String[]{"application/pdf", "application/vnd.ms-excel application/x-excel", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/vnd.ms-powerpoint", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "application/vnd.openxmlformats-officedocument.presentationml.presentation"};
    public static void chooseFile(final Activity activity, final int requestCode) {
        PermissionsCheckUtil.requestPermission(activity, new PermissionListener() {
            @Override
            public void permissionGranted(@NonNull String[] permission) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");//任意类型的
//                intent.putExtra(Intent.EXTRA_MIME_TYPES, types);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                activity.startActivityForResult(intent, requestCode);
            }

            @Override
            public void permissionDenied(@NonNull String[] permission) {

            }
        }, Manifest.permission.READ_EXTERNAL_STORAGE);
    }

    public static Intent openFile(String filePath) {

        File file = new File(filePath);
        if (!file.exists())
            return null;
        /* 取得扩展名 */
        String end = file.getName().substring(file.getName().lastIndexOf(".") + 1, file.getName().length()).toLowerCase(Locale.getDefault());
        /* 依扩展名的类型决定MimeType */
        if (end.equals("m4a") || end.equals("mp3") || end.equals("mid") || end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
            return getAudioFileIntent(filePath);
        } else if (end.equals("3gp") || end.equals("mp4")) {
            return getVideoFileIntent(filePath);
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png") || end.equals("jpeg") || end.equals("bmp")) {
            return getImageFileIntent(filePath);
        } else if (end.equals("apk")) {
            return getApkFileIntent(filePath);
        } else if (end.equals("ppt")) {
            return getPptFileIntent(filePath);
        } else if (end.equals("xls")) {
            return getExcelFileIntent(filePath);
        } else if (end.equals("doc")) {
            return getWordFileIntent(filePath);
        } else if (end.equals("pdf")) {
            return getPdfFileIntent(filePath);
        } else if (end.equals("chm")) {
            return getChmFileIntent(filePath);
        } else if (end.equals("txt")) {
            return getTextFileIntent(filePath, false);
        } else {
            return getAllIntent(filePath);
        }
    }

    // Android获取一个用于打开APK文件的intent
    public static Intent getAllIntent(String param) {

        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(new File(param));
        intent.setDataAndType(uri, "*/*");
        return intent;
    }

    // Android获取一个用于打开APK文件的intent
    public static Intent getApkFileIntent(String param) {

        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(new File(param));
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        return intent;
    }

    // Android获取一个用于打开VIDEO文件的intent
    public static Intent getVideoFileIntent(String param) {
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("oneshot", 0);
        intent.putExtra("configchange", 0);
        Uri uri = Uri.fromFile(new File(param));
        intent.setDataAndType(uri, "video/*");
        return intent;
    }

    // Android获取一个用于打开AUDIO文件的intent
    public static Intent getAudioFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("oneshot", 0);
        intent.putExtra("configchange", 0);
        Uri uri = Uri.fromFile(new File(param));
        intent.setDataAndType(uri, "audio/*");
        return intent;
    }

    // Android获取一个用于打开Html文件的intent
    public static Intent getHtmlFileIntent(String param) {

        Uri uri = Uri.parse(param).buildUpon().encodedAuthority("com.android.htmlfileprovider").scheme("content").encodedPath(param).build();
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.setDataAndType(uri, "text/html");
        return intent;
    }

    // Android获取一个用于打开图片文件的intent
    public static Intent getImageFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.fromFile(new File(param));
        intent.setDataAndType(uri, "image/*");
        return intent;
    }

    // Android获取一个用于打开PPT文件的intent
    public static Intent getPptFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.fromFile(new File(param));
        intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
        return intent;
    }

    // Android获取一个用于打开Excel文件的intent
    public static Intent getExcelFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.fromFile(new File(param));
        intent.setDataAndType(uri, "application/vnd.ms-excel");
        return intent;
    }

    // Android获取一个用于打开Word文件的intent
    public static Intent getWordFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.fromFile(new File(param));
        intent.setDataAndType(uri, "application/msword");
        return intent;
    }

    // Android获取一个用于打开CHM文件的intent
    public static Intent getChmFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.fromFile(new File(param));
        intent.setDataAndType(uri, "application/x-chm");
        return intent;
    }

    // Android获取一个用于打开文本文件的intent
    public static Intent getTextFileIntent(String param, boolean paramBoolean) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (paramBoolean) {
            Uri uri1 = Uri.parse(param);
            intent.setDataAndType(uri1, "text/plain");
        } else {
            Uri uri2 = Uri.fromFile(new File(param));
            intent.setDataAndType(uri2, "text/plain");
        }
        return intent;
    }

    // Android获取一个用于打开PDF文件的intent
    public static Intent getPdfFileIntent(String param) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.fromFile(new File(param));
        intent.setDataAndType(uri, "application/pdf");
        return intent;
    }

    public interface CallBack{
        void startLoadingDialog();
        void onDownloadProgress();//下载进度
        void endLoadingDialog();
    }
}
